package net.asfun.jvalog.frame;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

public class JdoFactory {

	private static final PersistenceManagerFactory pmf =
        JDOHelper.getPersistenceManagerFactory("jvalog");

	private static final ThreadLocal<PersistenceManager> pmHolder = new ThreadLocal<PersistenceManager>();
	
	public static final PersistenceManager open() {
		PersistenceManager pm = pmHolder.get();
		if ( pm == null ) {
			pm = pmf.getPersistenceManager();
			pmHolder.set(pm);
		}
		return pm;
	}
	
	public static final void txBegin() {
		PersistenceManager pm = open();
		if ( pm.currentTransaction().isActive() ) {
			return;
		}
		pm.currentTransaction().begin();
	}
	
	public static final void txRollback() {
		PersistenceManager pm = open();
		if ( pm.currentTransaction().isActive() ) {
			pm.currentTransaction().rollback();
		}
	}
	
	public static final void txCommit() {
		PersistenceManager pm = open();
		if ( pm.currentTransaction().isActive() ) {
			pm.currentTransaction().commit();
		}
	}
	
	public static final void close() {
		open().close();
		pmHolder.remove();
	}
	
	
}
